<template>
    <div class="pageContainer">
        <el-container class="bg-white rounded-lg">
            <el-header class="flex items-center justify-between" style="border-bottom: 1px solid #eeeeee;">
                <el-button type="primary" @click="onAdd">新增</el-button>
                <el-button type="primary" text @click="onSearch">
                    <el-icon :size="20">
                        <Refresh />
                    </el-icon>
                </el-button>
            </el-header>
            <el-container>
                <div class="w-full">
                    <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName">
                        <el-table-column label="序号" width="90" align="center" fixed="left" prop="rank">
                            <template #default="{ $index, row }">
                                {{ (currentPage - 1) * limit + $index + 1 }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="角色名称" min-width="200" />
                        <el-table-column prop="desc" label="角色描述" min-width="200" />
                        <el-table-column label="发布时间" width="300">
                            <template #default="{ row }">
                                {{ dayjs(row.create_time).format('YYYY-MM-DD HH:mm:ss') }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="状态" min-width="200">
                            <template #default="{ $index, row }">
                                <el-switch v-model="row.status" :active-value="1" :inactive-value="0" size="small"
                                    @change="onStatusChange(row)" />
                            </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" min-width="200" align="center">
                            <template #default="scope">
                                <el-button link type="primary" @click="onOpenRule(scope.row)">权限配置</el-button>
                                <el-button link type="primary" @click="onEdit(scope.row)">修改</el-button>
                                <el-popconfirm title="确定删除该角色吗？" @confirm="onDelete(scope.row)">
                                    <template #reference>
                                        <el-button type="primary" link>删除</el-button>
                                    </template>
                                </el-popconfirm>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div style="height: 50px;" class="flex items-center justify-center">
                        <el-pagination layout="prev, pager, next" background :current-page="currentPage"
                            :total="totalCount" :page-size="10" @current-change="onPageChange" />
                    </div>
                </div>
            </el-container>
        </el-container>
        <FormDrawer ref="drawerRef" :title="drawerTitle" @submit="onSubmit">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100">
                <el-form-item label="角色名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入角色标题" clearable />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
                </el-form-item>
                <el-form-item label="公告内容" prop="desc">
                    <el-input v-model="form.desc" type="textarea" placeholder="请输入角色内容" :rows="5" clearable />
                </el-form-item>
            </el-form>
        </FormDrawer>
        <!-- 权限配置 -->
        <FormDrawer ref="ruleDrawerRef" title="权限配置" @submit="onRuleSubmit">
            <el-tree-v2 ref="ruleTree" style="max-width: 600px" :data="ruleList" 
            :props="{label:'name', value:'id', children:'child'}"
            :default-expanded-keys="defaultExpandKyes"
            show-checkbox :height="500">
                <template #default="{ node, data }">
                    <div class="flex items-center w-full">
                        <el-tag size="small" :type="data.menu ? 'primary' : 'info'">{{ data.menu ? '菜单' : '权限'
                            }}</el-tag>
                        <span class="ml-2">{{ data.name }}</span>
                    </div>
                </template>
            </el-tree-v2>
        </FormDrawer>
    </div>
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue'
import dayjs from 'dayjs'
import { getRoleList, addRole, updateRoleById, deleteRoleById, upateRoleStatusById, setRules } from '../../api/role'
import { getRuleTree } from '../../api/rule'
import { toast, openFullScreenLoading, closeFullScreenLoading } from '../../composables/util'
import FormDrawer from '../../components/FormDrawer.vue'
import { useTableSearch, useForm } from '../../composables/common'

// 查询相关
// 定义查询表单
const searchform = reactive({
    keyword: "",
})

// 定义清除查询条件的表单
const clearSearchform = () => {
    searchform.keyword = ''
}

const {
    tableRowClassName,
    onSearch,
    getData,
    onClearSearch,
    onPageChange,
    currentPage,
    tableData,
    totalCount,
    limit
} = useTableSearch({
    searchform,
    getTableList: getRoleList,
    clearSearchform
})

// do not use same name with ref
const form = reactive({
    id: 0,
    name: '',
    desc: '',
    status: 1,
    create_time: '2022-06-11 15:32:10',
    update_time: '2022-06-11 15:32:10'
})

const rules = {
    name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
    desc: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
}

const {
    formRef,
    drawerRef,
    drawerTitle,
    onAdd,
    onEdit,
    onDelete,
    onSubmit,
    onStatusChange
} = useForm({
    title: '角色', // 功能名称
    form, // form表单，必须
    tableData, // 表单数据来源
    getData, // 更新表单数据接口
    add: addRole, // 新增接口
    update: updateRoleById, // 修改接口
    delete: deleteRoleById, // 删除接口
    updateStatus: upateRoleStatusById // 修改状态
})


// 权限管理
const ruleTree = ref(null) // 权限数的ref引用
const ruleList = ref(null)
const roleId = ref(0)
const roleRules = ref([])
const defaultExpandKyes = ref([]) // 默认展开
onMounted(() => {
    // 获取权限管理的tree菜单数据
    getRuleTree().then(res => {
        ruleList.value = res.data.list
        // defaultExpandKyes.value = res.data.list.map(item => item.id)
    })
})

const ruleDrawerRef = ref(null)
const onRuleSubmit = () => {
    openFullScreenLoading()
    setRules(roleId.value,  ruleTree.value.getCheckedKeys()).then(res=>{
        toast("设置权限成功")
        getData()
    }).finally(()=>{
        closeFullScreenLoading()
        ruleDrawerRef.value.close()
    })
}

// 打开权限配置页面
const onOpenRule = (row) => {
    roleId.value = row.id
    // console.log('row=', row)
    roleRules.value = JSON.parse(row.rule_ids)
    ruleDrawerRef.value.open()
    setTimeout(()=>{
        ruleTree.value.setCheckedKeys(roleRules.value)
    },150)
}


</script>
